const { db } = require('../../../其他内容/back-end/models/db');
const bcrypt = require('bcrypt');

// Define dummy data for database initialization
// Dummy data for 'users' table
const users = [
  {
    Username: 'Gina',
    Email: 'gina@example.com',
    Password: 'password123',
  },
  {
    Username: 'Yani',
    Email: 'yani@example.com',
    Password: 'password123',
  },
  {
    Username: 'Quinn',
    Email: 'quinn@example.com',
    Password: 'password123',
  },
  {
    Username: 'Iris',
    Email: 'iris@example.com',
    Password: 'password123',
  }
];

// Dummy data for 'groups' table
const groups = [
  {
    GroupName: 'Group A',
    Description: 'This is group A',
    Type:'Sports',
    AdminID: 1,
    Privacy: 'Public'
  },
  {
    GroupName: 'Group B',
    Description: 'This is group B',
    Type:'Academic',
    AdminID: '2',
    Privacy: 'Private'
  }
];

// Dummy data for 'members' table
const members = [
  {
    GroupID: 1,
    UserID: 1
  },
  {
    GroupID: 2,
    UserID: 2
  }
];

// Function to insert data into a table
function insertData(tableName, data) {
  return new Promise((resolve, reject) => {
    const insertedIds = [];
    let completed = 0;

    data.forEach((row, index) => {
      const keys = Object.keys(row);
      const values = Object.values(row);
      const placeholders = keys.map(() => '?').join(', ');

      db.run(
        `INSERT INTO "${tableName}" (${keys.join(', ')}) VALUES (${placeholders})`,
        values,
        function(err) {
          if (err) {
            console.error(`Failed to insert into ${tableName}:`, err);
            reject(err);
          }
          insertedIds[index] = this.lastID;
          completed++;
          if (completed === data.length) {
            resolve(insertedIds);
          }
        }
      );
    });
  });
}

// Function to sequentially insert all data
async function insertAllData() {
  try {
    console.log('Start inserting user data');
    const userIds = [];

    for (let i = 0; i < users.length; i++) {
      const user = users[i];
      // Hash the password
      const hash = await bcrypt.hash(user.Password, 10);
      console.log(`Password for user ${user.Username} has been encrypted`);

      const values = [user.Username, user.Email, hash];
      const userId = await new Promise((resolve, reject) => {
        db.run(
          'INSERT INTO users (Username, Email, Password) VALUES (?, ?, ?)',
          values,
          function(err) {
            if (err) {
              console.error('User insertion failed:', err);
              reject(err);
              return;
            }
            console.log(`User ${user.Username} inserted successfully, ID: ${this.lastID}`);
            resolve(this.lastID);
          }
        );
      });
      userIds.push(userId);

      // Insert corresponding student records
      const studentData = {
        StudentId: userId,  // Use the user's ID as the StudentId
        Photo:'images/default_photo.jpg',
        Bio: null,
        Interests: null,
        Courses: null,
        Achievements: null,
      };
      await insertData('students', [studentData]);
      console.log(`Student record for user ${user.Username} created successfully, ID: ${userId}`);
    }

    console.log('User data insertion successful! User IDs:', userIds);

    // Insert group data
    console.log('Start inserting group data');
    await insertData('groups', groups);
    console.log('Group data insertion successful!');

    await insertData('members', members);

  } catch (error) {
    console.error('Data insertion failed:', error);
    throw error;
  }
}

// Export the function
module.exports = { insertAllData };

// Perform data insertion
insertAllData().catch(console.error);
